package cn.whit.blog.service.impl;

import java.sql.SQLException;
import java.util.List;

import cn.whit.blog.dao.VoteDao;
import cn.whit.blog.dao.VoteItemDao;
import cn.whit.blog.domain.User;
import cn.whit.blog.domain.Vote;
import cn.whit.blog.service.VoteService;
import cn.whit.blog.util.BeanFactory;
import cn.whit.blog.util.DynamicQuery;
import cn.whit.blog.util.PageModel;

public class VoteServiceImpl implements VoteService {

	VoteDao voteDao = (VoteDao)BeanFactory.createObject("voteDao");
	
	VoteItemDao voteItemDao = (VoteItemDao)BeanFactory.createObject("voteItemDao");
	
	@Override
	public Vote findById(String id) throws SQLException {
		return voteDao.findById(id);
	}

	@Override
	public List<Vote> findAll() throws SQLException {
		return voteDao.findAll();
	}

	@Override
	public List<Vote> findAllWithPageAndQuery(int startIndex, int pageSize, DynamicQuery query) throws Exception {
		return voteDao.findAllWithPageAndQuery(startIndex, pageSize, query);
	}

	@Override
	public int findTotalRecordsAndQuery(DynamicQuery query) throws Exception {
		return voteDao.findTotalRecordsAndQuery(query);
	}

	@Override
	public void save(Vote vote) throws SQLException {
		voteDao.save(vote);
	}

	@Override
	public void update(Vote vote) throws SQLException {
		voteDao.update(vote);
	}

	@Override
	public PageModel findByPageAndQuery(int startIndex, int pageSize, DynamicQuery query) throws Exception {
		//startIndex 从第一页，索引 1 开始
		int totalRecords = voteDao.findTotalRecordsAndQuery(query);
		PageModel pm = new PageModel(startIndex,totalRecords,pageSize);
		List<Vote> list = voteDao.findAllWithPageAndQuery(pm.getStartIndex(),pm.getPageSize(),query);
		pm.setList(list);
		pm.setUrl("VoteServlet?method=list");
		return pm;
	}
	
	@Override
	public PageModel findByPageAndQuery2(int startIndex, int pageSize, DynamicQuery query) throws Exception {
		//startIndex 从第一页，索引 1 开始
		int totalRecords = voteDao.findTotalRecordsAndQuery(query);
		PageModel pm = new PageModel(startIndex,totalRecords,pageSize);
		List<Vote> list = voteDao.findAllWithPageAndQuery(pm.getStartIndex(),pm.getPageSize(),query);
		pm.setList(list);
		pm.setUrl("VoteServlet?method=voteList");
		return pm;
	}

	@Override
	public Vote getById(String id) throws SQLException {
		return voteDao.findById(id);
	}

	@Override
	public void deleteById(String s) throws SQLException {
		// 删除投票的时候，需要先把该投票的投票选项都删除
		voteItemDao.deleteByVoteId(s);
		voteDao.deleteById(s);
	}

}
